package controller;

import java.io.File;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;


@Controller
public class TerrariaController {

	@Value("#{terraria.map}")
	private String map;
	
	@Value("#{terraria.upload_path}")
	private String uploadMap;
	
	/**
	 * 下载游戏地图
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("terraria_map_download")
	public ResponseEntity<byte[]> terraria_map_download() throws IOException {
		File mapfile = new File(map);
		HttpHeaders headers = new HttpHeaders();
		headers.setContentDispositionFormData("attachment", "utopia.wld");
		headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
		return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(mapfile),headers, HttpStatus.CREATED);
	}
	
	@ResponseBody
	@RequestMapping("terraria_upload_map")
	public String uploadMap(@RequestParam(value="upload_map_file")MultipartFile file,HttpServletRequest request) throws IllegalStateException, IOException{
		if(file.isEmpty()){
			return null;
		}else{
			String fileName =System.currentTimeMillis()+"_"+ file.getOriginalFilename();
			String filepathstr = uploadMap+File.separatorChar+fileName;
			file.transferTo(new File(filepathstr));
			return "success!";
		}
		
	}

}
